package com.wym.learning;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Wu_youming on 2015/4/28.
 * Everyday is another day, keep going.
 */
public class PlayService extends Service {
    private final String TAG = "PlayService";
    private MyReceiver myReceiver;
    private ArrayList<MusicModel> music_list = new ArrayList<MusicModel>();
    private MediaPlayer mediaPlayer;
    private int current = 0;
    private SharedPreferences share;
    private Handler handle;
    private Runnable runnable;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.v(TAG, "onCreate");
        super.onCreate();
        //动态注册broadcastReceiver
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter(MainActivity.ACTION);
        registerReceiver(myReceiver, filter);

        //获取歌曲文件
        getMusicFiles();

    }

    @Override
    public void onDestroy() {
        Log.v(TAG, "onDestroy");
        if (mediaPlayer != null) {
            System.out.println("currentPosition-->" + mediaPlayer.getCurrentPosition());
            share.edit().putInt("current", current).putInt("duration", mediaPlayer.getCurrentPosition()).apply();
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        handle.removeCallbacks(runnable);
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        Log.v(TAG, "onStartCommand");
        //获取历史播放记录
        share = getSharedPreferences("playData", MODE_PRIVATE);
        current = share.getInt("current", 0);
        int duration = share.getInt("duration", 0);
        //告知当前播放的歌曲位置
        Intent i = new Intent(MainActivity.UPDATE);
        i.putExtra("update", 0x1006);
        i.putExtra("current", current);
        sendBroadcast(i);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
        playMusic();

        mediaPlayer.seekTo(duration);
        runnable = new Runnable() {
            @Override
            public void run() {

                Intent intent1 = new Intent(MainActivity.UPDATE);
                int progress = (int) (mediaPlayer.getCurrentPosition() / (float) mediaPlayer.getDuration() * 100);
                intent1.putExtra("update", 0x1005);
                intent1.putExtra("progress", progress);
                sendBroadcast(intent1);
                handle.postDelayed(runnable, 500);
            }
        };
        handle = new Handler();
        handle.postDelayed(runnable, 500);
        return super.onStartCommand(intent, flags, startId);

    }

    //获取歌曲文件
    private void getMusicFiles() {
        String[] music = new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DATA};
        Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, music, null, null, null);
        while (cursor.moveToNext()) {
            MusicModel model = new MusicModel();

            String[] names = cursor.getString(1).split("\\.");
            model.setName(names[0]);
            model.setTitle(cursor.getString(2));
            model.setDuration(cursor.getInt(3));
            model.setArtist(cursor.getString(4));
            model.setData(cursor.getString(5));
            if (model.getDuration() > 15000)
                music_list.add(model);

        }
    }

    //广播接收器
    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int control = intent.getIntExtra("control", -1);
            Intent tmp = new Intent(MainActivity.UPDATE);
            switch (control) {
                case 0x10010://上一曲
                    if (current == 0)
                        current = music_list.size() - 1;
                    else
                        current--;
                    playMusic();
                    tmp.putExtra("update", 0x1006);
                    tmp.putExtra("current", current);
                    break;
                case 0x10011: //播放状态切换
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        tmp.putExtra("update", 0x1003);

                    } else {
                        mediaPlayer.start();
                        tmp.putExtra("update", 0x1000);
                    }
                    sendBroadcast(tmp);
                    break;
                case 0x10012://下一曲
                    if (current == music_list.size() - 1)
                        current = 0;
                    else
                        current++;
                    playMusic();
                    tmp.putExtra("update", 0x1006);
                    tmp.putExtra("current", current);
                    break;
                case 0x10013://播放进度调整
                    int progress = intent.getIntExtra("progress", 0);
                    mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100);
//                    tmp.putExtra("update", 0x1005);
                    break;
                case 0x10015://点播
                    current = intent.getIntExtra("current", 0);
                    playMusic();
                    tmp.putExtra("update", 0x1006);
                    tmp.putExtra("current", current);
                    break;
                default:
                    break;
            }
            sendBroadcast(tmp);
        }
    }

    //播放音乐
    private void playMusic() {
        mediaPlayer.reset();
        try {
            if (!music_list.isEmpty()) {
                mediaPlayer.setDataSource(music_list.get(current).getData());
                mediaPlayer.prepare();
                mediaPlayer.start();
                mediaPlayer.setOnCompletionListener(new PlayerOnCompletionListener());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //mediaPayer的完成监听方法
    private class PlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            //播放完成时，自动播放下一曲
            current++;
            if (current == music_list.size())
                current = 0;
            Intent i = new Intent(MainActivity.UPDATE);
            i.putExtra("update", 0x1006);
            i.putExtra("current", current);
            sendBroadcast(i);
            playMusic();
        }
    }
}
